package com.cgwx.systemservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cgwx.systemservice.entity.sys.SysRole;
import com.cgwx.systemservice.entity.sys.SysUserRole;
import com.cgwx.systemservice.entity.vo.AssginRoleVo;
import com.cgwx.systemservice.mapper.SysRoleMapper;
import com.cgwx.systemservice.mapper.SysUserRoleMapper;
import com.cgwx.systemservice.service.SysUserRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户角色 服务实现类
 * </p>
 *
 * @author GaoWei
 * @since 2023-10-12
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements SysUserRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;

//    根据用户ID获取用户角色
    @Override
    public Map<String, Object> getRolesByUserId(Long userId) {
//        查询所有角色
        List<SysRole> sysRoleList = sysRoleMapper.selectList(null);
//        根据用户id查询当前用户已经分配的角色
        QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        List<SysUserRole> sysUserRoleList = baseMapper.selectList(queryWrapper);
//        从集合中，获取所有角色id
        List<Long> userRoleIds = new ArrayList<>();
        for (SysUserRole sysUserRole : sysUserRoleList) {
            userRoleIds.add(sysUserRole.getRoleId());
        }
//        封装到Map中
        Map<String, Object> returnMap = new HashMap<>();
//        封装所有角色
        returnMap.put("allRoles",sysRoleList);
//        封装当前用户已分配的角色
        returnMap.put("userRoleIds",userRoleIds);
        return returnMap;
    }

//    为用户分配角色
    @Override
    public void doAssign(AssginRoleVo assginRoleVo) {
//        根据用户id删除之前分配的角色
        QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", assginRoleVo.getUserId());
        baseMapper.delete(queryWrapper);
//        获取当前用户所有角色id，添加角色用户关系表
        List<Long> roleIdList = assginRoleVo.getRoleIdList();
        for (Long roleId : roleIdList) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(assginRoleVo.getUserId());
            sysUserRole.setRoleId(roleId);
            baseMapper.insert(sysUserRole);
        }
    }
}
